package TukuduDemo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;


public class UserDAO {
	
	private static Logger log = Logger.getLogger(UserDAO.class.getName());
	private Connection connection;
	private Statement statement;
	private PreparedStatement preparedstatement;
	
	public User getUser(int user_id){
		String query = "SELECT * FROM User WHERE user_id = " + user_id + ";";
		ResultSet rs = null;
		User user = null;
		
		try{
			connection = ConnectionFactory.getConnection();
			statement = connection.createStatement();
			rs = statement.executeQuery(query);
			if(rs.next()){
				user = new User();
				user.setUserId(rs.getInt("user_id"));
				user.setUserName(rs.getString("user_name"));
				user.setFirstName(rs.getString("first_name"));
				user.setLastName(rs.getString("last_name"));
				user.setEmail(rs.getString("email"));
				user.setPassword(rs.getString("password"));
				user.setUserType(rs.getString("user_type"));
				user.setActiveFlag(rs.getString("active_flag"));
				user.setCreatedBy(rs.getInt("created_by"));
				user.setCreatedDate(rs.getDate("created_date"));
				user.setModifiedBy(rs.getInt("modified_by"));
				user.setModifiedDate(rs.getDate("modified_date"));
				user.setDOB(rs.getDate("date_of_birth"));
				user.setCoins(rs.getInt("coins"));
				user.setNOB(rs.getInt("no_of_businesses"));
			}
			
			System.out.println(user);
		}catch(SQLException e){
			e.printStackTrace();
			log.debug("SELECT Query Unsuccessful; Query:" + query);
			
			log.debug("Due To: " + e);
		}
		finally{
			//DbUtil.close(rs);
			//DbUtil.close(statement);
			//DbUtil.close(connection);
		}
		return user;
	}
	
	public boolean saveUser(){
		boolean val = false;
		String insertQuery = "INSERT INTO User (user_id, user_name, first_name, last_name, email, password, user_type, active_flag, created_by, created_date, modified_by, modified_date, date_of_birth, coins, no_of_businesses) VALUES(4, 'bhawana', 'Bhawana', 'Negi', 'bhawana.negi@facebook.com', 'Negative!4', 'A', 'Y', 0, '2013-04-25 12:58:08', 0, '2013-09-03 07:02:25', '1989-12-10', 1600, 90);";
	
		try{
			connection=ConnectionFactory.getConnection();
			statement= connection.createStatement();
			System.out.println(insertQuery);
			val=statement.execute(insertQuery);
			
		}catch(SQLException se){
			se.printStackTrace();
		}
		
		return val;
	}
	
	public boolean deleteUser(int id){
		boolean val=false;
		String deleteQuery = "DELETE FROM User WHERE user_id = " + id;
		try{
			connection = ConnectionFactory.getConnection();
			statement = connection.createStatement();
			System.out.println(deleteQuery);
			val = statement.execute(deleteQuery);
			System.out.println(val);
		}catch(SQLException se){
			se.printStackTrace();
		}
		return val;
	}
}
